package models

import (
	"fmt"
	"errors"
	"git.oschina.net/YPTArch/auth/sys/logs"
	"git.oschina.net/YPTArch/auth/libs/base64"
	"git.oschina.net/YPTArch/auth/libs/encrypt"
	"time"
)

//远程生成Token 请求
type GenerateTokenRequest struct {
	// 用户信息
	User User
	// 是否生成刷新Token
	IsGenRefresh bool
}
type GenerateTokenByRefreshTokenRequest struct {
	// 刷新Token
	RefreshToken string
}

//远程生成Token 返回
type GenerateTokenResponse struct {
	// token
	Access string
	// token创建时间
	AccessCreateAt time.Time
	// token过期时间
	AccessExpiresIn time.Duration
	// refresh token
	Refresh string
	// refresh token 创建时间
	RefreshCreateAt time.Time
	// refresh token 过期时间
	RefreshExpiresIn time.Duration
}

//生成token
func GenerateToken(plaintext string) (string, error) {
	cipherText, err := encrypt.AesEncrypt([]byte(plaintext))
	if err != nil {
		logs.Logger.Error(fmt.Sprintf("lib/encrypt/AesEncrypt() Error:  %s", err.Error()))
		return "", errors.New("生成token失败")
	}
	cipherString := base64.Base64Encode(cipherText)

	return cipherString, nil
}

//解析token
func ParsingToken(cipherString string) (string, error) {

	ciphertext, err := base64.Base64Decde(cipherString)
	if err != nil {
		logs.Logger.Error(fmt.Sprintf("lib/encrypt/AesDecrypt()  Error:  %s", err.Error()))
		return "", errors.New("传递的token不正确")
	}

	plaintext, err := encrypt.AesDecrypt(ciphertext)
	if err != nil {
		logs.Logger.Error(fmt.Sprintf("models/Parsingtoken() AesDecrypt err:Error: %s", err.Error()))
		return "", errors.New("token不正确")
	}

	return string(plaintext), nil
}
